package servlet;

import com.alibaba.fastjson.JSON;
import pojo.Contact;
import service.ContactService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * 为用户添加联系人记录
 * 输入一个Person对象，将该对象添加到数据库中，需要修改两个表：person和up，存在就不添加，不存在就得添加，最后一定成功，忽略任何异常
 * 添加成功返回true，否则返回false
 */
@WebServlet("/addContactServlet")
public class AddContactServlet extends HttpServlet {
    private final ContactService contactService = new ContactService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = request.getReader();
        String jsonString = reader.readLine();
        Contact contact = JSON.parseObject(jsonString, Contact.class);

        List<Contact> contacts = contactService.selectContactOfID(contact);

        if (contacts.isEmpty())
            contactService.addContact(contact);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
